package com.lijing.Partition;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @title: RestoreIpAddress
 * @Author LiJing
 * @Date: 2021/4/69:52 下午
 * @Version 1.0
 */
public class RestoreIpAddress {
    static List<StringBuilder> result = new ArrayList<>();
    static StringBuilder path = new StringBuilder();
    static int count = 0;
    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("255255a1135");
        if (isNumber(str)){
            backTracing(0,str);
            System.out.println(result);
        }else {
            System.out.println("待转换的字符串不合法！");
        }

    }

    public static void backTracing(int startIndex, StringBuilder str){
        //end condition
        if (count == 3){
            if (isIP(str,startIndex,str.length())){
                result.add(new StringBuilder(str));
            }
            return;
        }

        for (int i = startIndex; i < str.length(); i++) {
            //处理当前节点
            if (isIP(str,startIndex,i+1)){
                str.insert(i+1,".");
                count++;
                backTracing(i+2,str);
                str.delete(i+1,i+2);
                count--;
            }else {
                break;
            }

        }

    }

    /**
     *
     * @param s s
     * @param start start index
     * @param end end index
     * @return true/false
     */
    public static boolean isIP(StringBuilder s, int start, int end){
        boolean charge1 = end - start > 1 &&
                (Integer.parseInt(s.substring(start,start+1)) == 0 ||
                        Integer.parseInt(s.substring(start,end)) > 255);
        if (charge1){
            return false;
        }
        return true;
    }

    /**
     * 判断是否是有效的ip地址
     * @param s
     * @return
     */
    public static boolean isNumber(StringBuilder s){
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) > '9' || s.charAt(i) < '0'){
                return false;
            }
        }
        return true;
    }
}
